//
//  XYTextField.m
//  UITest
//
//  Created by yao zhaofeng on 2018/5/31.
//  Copyright © 2018年 YaoZhaofeng. All rights reserved.
//

#import "XYTextField.h"

@implementation XYTextField

- (void)setCursorPosition:(int)position {
    NSRange range = NSMakeRange(position, 0);
    [self setSelectedRange:range];
}

- (int)getCursorPosition {
    
    NSRange range = [self selectedRange];
    NSUInteger position = range.location + range.length;
    
    return (int)position;
}

- (NSRange) selectedRange
{
    UITextPosition* beginning = self.beginningOfDocument;
    
    UITextRange* selectedRange = self.selectedTextRange;
    UITextPosition* selectionStart = selectedRange.start;
    UITextPosition* selectionEnd = selectedRange.end;
    
    NSInteger location = [self offsetFromPosition:beginning toPosition:selectionStart];
    NSInteger length = [self offsetFromPosition:selectionStart toPosition:selectionEnd];
    
    return NSMakeRange(location, length);
}

- (void) setSelectedRange:(NSRange) range
{
    UITextPosition* beginning = self.beginningOfDocument;
    
    UITextPosition* startPosition = [self positionFromPosition:beginning offset:range.location];
    UITextPosition* endPosition = [self positionFromPosition:beginning offset:range.location + range.length];
    UITextRange* selectionRange = [self textRangeFromPosition:startPosition toPosition:endPosition];
    
    [self setSelectedTextRange:selectionRange];
}

- (void)setText:(NSString *)text {
    if (![text isEqualToString:self.text]) {
        UITextRange *selection = self.selectedTextRange;
        NSInteger oldTextLength = self.text.length;
        [super setText:text];
        if (selection.empty) {
            // maintain cursor position relative to the end of the old text
            NSInteger start = [self offsetFromPosition:self.beginningOfDocument toPosition:selection.start];
            NSInteger offsetFromEnd = oldTextLength - start;
            NSInteger newOffset = text.length - offsetFromEnd;
            UITextPosition *position = [self positionFromPosition:self.beginningOfDocument offset:newOffset];
            [self setSelectedTextRange:[self textRangeFromPosition:position toPosition:position]];
        }
    }
}

@end
